package cn.gailvlun.gll.presentation.chat;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.view.View;

import com.github.markzhai.recyclerview.BaseViewAdapter;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadmoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.util.List;

import cn.gailvlun.gll.R;
import cn.gailvlun.gll.databinding.ActivityRoomMemberBinding;
import cn.gailvlun.gll.net.HttpMethods;
import cn.gailvlun.gll.net.HttpSubscriber;
import cn.gailvlun.gll.net.ListRes;
import cn.gailvlun.gll.net.Member;
import cn.gailvlun.gll.net.NewQueryParam;
import cn.gailvlun.gll.presentation.base.BaseActivity;
import cn.gailvlun.gll.presentation.chat.adapter.RoomMemberAdapter;
import cn.gailvlun.gll.util.DialogUtil;
import cn.gailvlun.gll.util.IsEmpty;
import cn.gailvlun.gll.util.RxUtil;
import cn.gailvlun.gll.widget.NavigationBarView;
import io.reactivex.functions.Consumer;
import rx_activity_result2.Result;
import rx_activity_result2.RxActivityResult;



public class RoomMemberActivity extends BaseActivity implements OnRefreshListener, OnLoadmoreListener {

    public static String EXTRA_CAN_AT_ALL = "EXTRA_CAN_AT_ALL";
    public static String EXTRA_AT_ALL = "EXTRA_AT_ALL";

    public static void openActivity(Context context, int roomId) {
        Intent intent = new Intent(context, RoomMemberActivity.class);
        intent.putExtra("roomId", roomId);
        context.startActivity(intent);
    }

    public static void openActivity(BaseActivity activity, int roomId, boolean canAtAll, Consumer<Result<BaseActivity>> consumer) {
        Intent intent = new Intent(activity, RoomMemberActivity.class);
        intent.putExtra("roomId", roomId);
        intent.putExtra(EXTRA_CAN_AT_ALL, canAtAll);
        RxActivityResult.on(activity)
                .startIntent(intent)
                .subscribe(consumer);
    }

    private ActivityRoomMemberBinding mBinding;
    private RoomMemberAdapter mAdapter;
    private LinearLayoutManager mLayoutManager;

    private int mRoomId;
    private boolean mCanAtAll;

    private NewQueryParam newQueryParam = new NewQueryParam();

    @Override
    protected void initComponent() {
        mBinding = DataBindingUtil.setContentView(this, R.layout.activity_room_member);

        mAdapter = new RoomMemberAdapter(mContext);
        mAdapter.setPresenter(new Presenter());
        mBinding.recyclerView.setAdapter(mAdapter);

        mLayoutManager = new LinearLayoutManager(mContext);
        mBinding.recyclerView.setLayoutManager(mLayoutManager);

        mBinding.srl.setOnRefreshListener(this);
        mBinding.srl.setOnLoadmoreListener(this);
        mBinding.srl.setEnableLoadmore(false);
    }

    @Override
    protected void createHandler() {
        mBinding.nbv.setOnBackListener(new NavigationBarView.OnBackListener() {
            @Override
            public void onBack(NavigationBarView nb) {
                onBackPressed();
            }
        });
        mBinding.nbv.setOnMenuClickListener(new NavigationBarView.OnMenuClickListener() {
            @Override
            public void onMenuClick(NavigationBarView nb) {
                Intent intent=new Intent();
                intent.putExtra(EXTRA_AT_ALL,true);
                intent.putIntegerArrayListExtra(EXTRA_PROFILE_IDs,mAdapter.getProfileIds());
                setResult(Activity.RESULT_OK,intent);
                finish();
            }
        });
    }

    @Override
    protected void loadData(@Nullable Bundle savedInstanceState) {
        mRoomId = getIntent().getIntExtra("roomId", -1);
        mCanAtAll = getIntent().getBooleanExtra(EXTRA_CAN_AT_ALL, false);
        if (mCanAtAll){
            mBinding.nbv.setMenuEnable(true);
            mBinding.nbv.setMenuText("全选");
            mBinding.nbv.setMenuTextColor(R.color.blue);
        }
        if (mRoomId == -1) {
            finish();
        }

        mBinding.srl.autoRefresh();
    }

    @Override
    public void onRefresh(RefreshLayout refreshlayout) {
        HttpMethods.getMemberService()
                .getMemberList(mRoomId, true, null, null, 150)
                .compose(RxUtil.<ListRes<Member>>applyScheduler())
                .subscribe(new HttpSubscriber<ListRes<Member>>() {
                    @Override
                    protected void onSuccess(ListRes<Member> response) {
                        loadRecyclerView(response.getResults(), true, response.isNext());
                    }

                    @Override
                    protected void onFailure(String errMsg, @Nullable ListRes<Member> response, int code) {
                        DialogUtil.showError(mContext, errMsg);
                    }

                    @Override
                    protected void onFinish() {
                        super.onFinish();
                        mBinding.srl.finishRefresh();
                    }
                });
    }

    @Override
    public void onLoadmore(RefreshLayout refreshlayout) {
        newQueryParam.setLastId(mAdapter.getLastId());
        HttpMethods.getMemberService()
                .getMemberList(mRoomId, true, newQueryParam.getLastId(), newQueryParam.getDirection(), 150)
                .compose(RxUtil.<ListRes<Member>>applyScheduler())
                .subscribe(new HttpSubscriber<ListRes<Member>>() {
                    @Override
                    protected void onSuccess(ListRes<Member> response) {
                        loadRecyclerView(response.getResults(), false, response.isNext());
                    }

                    @Override
                    protected void onFailure(String errMsg, @Nullable ListRes<Member> response, int code) {
                        DialogUtil.showError(mContext, errMsg);
                    }

                    @Override
                    protected void onFinish() {
                        super.onFinish();
                        mBinding.srl.finishLoadmore();
                    }
                });
    }

    private void loadRecyclerView(List<Member> members, boolean isRefresh, boolean isMore) {
        if (isRefresh) {
            if (IsEmpty.list(members)) {
                mAdapter.clear();
            } else {
                mAdapter.set(members);
            }
        } else {
            mAdapter.addAll(members);
        }

        mBinding.srl.setEnableLoadmore(isMore);
    }

    public static class Util {
        public static String getTitleName(Member item) {
            return "房主";
        }

        public static int getTitleVisibility(Member item) {
            if (item.isIs_host()) {
                return View.VISIBLE;
            } else {
                return View.GONE;
            }
        }
    }

    public static String EXTRA_MEMBER_ID = "extra_member_id";
    public static String EXTRA_PROFILE_ID = "extra_profile_id";
    public static String EXTRA_PROFILE_IDs = "extra_profile_ids";
    public static String EXTRA_MEMBER_NICK_NAME = "extra_member_name";

    public class Presenter implements BaseViewAdapter.Presenter {
        public void onAtWhom(Member member) {
            Intent intent = new Intent();
            intent.putExtra(EXTRA_PROFILE_ID, member.getOwner().getId());
            intent.putExtra(EXTRA_MEMBER_ID, member.getId());
            intent.putExtra(EXTRA_MEMBER_NICK_NAME, member.getNickname());
            setResult(Activity.RESULT_OK, intent);
            finish();
        }
    }
}
